from fastapi import APIRouter, Query, Request, Depends
from sqlalchemy.orm import Session
from typing import List
from utils.response import success, fail, tableinfo
from utils.request import PageInfo, QueryWrapper
from utils.database import get_db
from app.model import RoleModel
from app.schema import RoleData

roleController = APIRouter()

@roleController.post("/add")
async def add_data(data: RoleData, db: Session = Depends(get_db)):
    """
    增加角色
    """
    try:
        r = RoleModel.insert(db, data)
        return success("添加成功")
    except Exception as e:
        return fail("添加失败："+str(e))

@roleController.post("/edit")   
async def edit_data(data: RoleData, db: Session = Depends(get_db)):
    """
    修改角色
    """
    try:
        row = data.dict(exclude_unset=True)
        r = RoleModel.edit(db, row)
        return success("修改成功")
    except Exception as e:
        return fail("修改失败："+str(e))
    
@roleController.post("/delete")   
async def delete_data(ids:List[int], db: Session = Depends(get_db)):
    """
    修改角色
    """
    try:
        r = RoleModel.delete(db, ids)
        return success("删除成功")
    except Exception as e:
        return fail("删除失败："+str(e))

@roleController.get("/selectoptions")
async def get_select(db = Depends(get_db)):
    options = RoleModel.get_select_options(db)
    return success("操作成功", options)


@roleController.get("/get")
async def get_one(id:int,  db: Session = Depends(get_db)):
    row = RoleModel.get_by_id(db, id)
    return success("操作成功", row)


@roleController.get("/menus")
async def get_one(id:int,  db: Session = Depends(get_db)):
    row = RoleModel.get_role_menus(db, id)

    return success("操作成功",[v.menu_id for v in row])


@roleController.get("/page")
async def get_page( page:int=Query(default=1), limit:int=Query(default=10), filter:str=Query(default='{}'), db: Session = Depends(get_db)):
    page  = PageInfo(page, limit)
    where = QueryWrapper.build_query_wrapper(filter)
    total, rows = RoleModel.get_page(db, where, page)
    return tableinfo("查询成功", total, rows)

@roleController.get("/list")
async def get_page(db: Session = Depends(get_db)):
    rows = RoleModel.get_role_list(db)
    return success("操作成功",rows)